import axios from 'axios'
import { Toast } from 'vant'
import Cookies from 'js-cookie'
import router from '../router'

// create an axios instance
const service = axios.create({
  baseURL: (process.env.NODE_ENV !== 'production' ? '' : 'http://nnh.letuy.cn/index.php/'),
  // baseURL: 'http://nnh.letuy.cn/index.php/',
  // headers: {
  //   post: {
  //     'Content-Type': 'application/x-www-form-urlencoded'
  //   }
  // },
  timeout: 10000
})

// http request 拦截器
service.interceptors.request.use(
  config => {
    // 发送请求之前做一些处理
    const token = Cookies.get('token')
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  }, error => {
    // 当请求异常时做一些处理
  return Promise.reject(error)
})

// http response 拦截器
service.interceptors.response.use((response, promise) => {
  if (response.status === 200 && typeof response.headers.authorization !== 'undefined') {
    Cookies.set('token', response.headers.authorization)
  }
  return Promise.resolve(response.data)
}, (err, promise) => {
  if (err.response.status === 401) {
    Toast({
      message: '用户未登录！',
      type: 'fail'
    })
    router.push({path: 'login'})
  } else if (err.response.status === 422) {
    for (let i in err.response.data.errors) {
      Toast({
        message: err.response.data.errors[i],
        type: 'fail'
      })
    }
  } else if (err.response.status === 500) {
    Toast('服务器开小差')
  } else {
    if (err.response.status !== 200) {
      Toast(err.response.data.message)
    }
  }
  return Promise.reject(err)
})

export default service
